//
//  ViewController.m
//  手机拍服务
//
//  Created by 企友软mac on 2018/2/3.
//  Copyright © 2018年 企友软mac. All rights reserved.
//

#import "TakePhotoViewController.h"
#import "ToolView.h"
#import "IQKeyboardManager.h"
#import "myTextCell.h"
#import "myImageCell.h"
#import "voiceCell.h"
#import "MessageTableView.h"
#import "HistoryMessageLog.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"

typedef enum : NSUInteger {
    SendText,
    SendImage,
    SendVoice

} MySendContentType;

@interface TakePhotoViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITableViewDataSource,UITableViewDelegate> {

    HistoryMessageLog *messageFrist;
    int j;
}

//工具栏
@property (nonatomic,strong) ToolView *toolView;
//工具栏的高约束，用于当输入文字过多时改变工具栏的约束
@property (strong, nonatomic) NSLayoutConstraint *tooViewConstraintHeight;
//从相册获取图片
@property (strong, nonatomic) UIImagePickerController *imagePiceker;
@property (weak, nonatomic) IBOutlet MessageTableView *chatTableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *constaintH;

//聊天的数据，一开始要从数据库中取出赋值
@property(nonatomic,strong)NSMutableArray *messageData;

//刷新
@property (assign,nonatomic)BOOL isRefresh;
@property (strong,nonatomic)UIActivityIndicatorView *activity;
@property (strong,nonatomic)NSMutableArray *timeArray;
@property (assign,nonatomic)BOOL isFirst;

@end

@implementation TakePhotoViewController

//懒加载
-(NSMutableArray *)timeArray
{
    if (!_timeArray) {
        _timeArray = [[NSMutableArray alloc]init];
    }
    return _timeArray;
}

-(NSMutableArray *)messageData
{
    if (!_messageData) {
        _messageData = [[NSMutableArray alloc]init];
    }
    return _messageData;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    //选图片
    self.imagePiceker = [[UIImagePickerController alloc] init];
    self.imagePiceker.allowsEditing = YES;
    self.imagePiceker.delegate = self;
    self.isFirst = YES;

    self.view.backgroundColor = [UIColor whiteColor];
    //工具栏
    self.toolView = [[ToolView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:self.toolView];

    //添加基本的子视图
    [self addMySubView];

    //给子视图添加约束
    [self addConstaint];
    //设置工具栏的回调
    [self setToolViewBlock];

    self.chatTableView.delegate = self;
    self.chatTableView.dataSource = self;

    [self.chatTableView.superview insertSubview:[UIView new] atIndex:0];

    //初始化data,需要从数据库中取出聊天记录
    [self initData];

    //获取通知中心
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    //注册为被通知者
    [notificationCenter addObserver:self selector:@selector(keyChange:) name:UIKeyboardWillChangeFrameNotification object:nil];

    //注册tap手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyBoardDown:)];

    [self.chatTableView addGestureRecognizer:tap];
}

-(void)initData
{
    //把bodyDic转换成data类型
    NSError *error = nil;
    NSData *bodyData = [NSJSONSerialization dataWithJSONObject:@{@"type":[NSNumber numberWithInteger:0],@"content":@"Hi，您好，请将您出现的故障手机拍照后，进行上传"} options:NSJSONWritingPrettyPrinted error:&error];
    if (error)
    {
        WLog(@"解析错误%@", [error localizedDescription]);
    }

    //把data转成字符串进行发送
    NSString *bodyString = [[NSString alloc] initWithData:bodyData encoding:NSUTF8StringEncoding];
    messageFrist = [[HistoryMessageLog alloc]init];
    messageFrist.body = bodyString;
    messageFrist.from = @"test";
    messageFrist.to = @"test";
    messageFrist.tab = [NSNumber numberWithBool:0];
    messageFrist.time = [NSDate date];
    //添加到数组里，刷新
    [self.messageData addObject:messageFrist];
    [self.timeArray addObject:messageFrist.time];
}

-(void)addMySubView
{
    //工具栏
    self.toolView = [[ToolView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:self.toolView];

    self.automaticallyAdjustsScrollViewInsets = false;  //第一个cell和顶部有留白，scrollerview遗留下来的，用来取消它
    //刷新控件
    UILabel *lbPrompt = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
    lbPrompt.backgroundColor = WRGBColor(253, 239, 212);
    [lbPrompt setText:@"下拉查看历史记录"];
    [lbPrompt setFont:[UIFont systemFontOfSize:13]];
    lbPrompt.textAlignment = NSTextAlignmentCenter;
    self.chatTableView.tableHeaderView = lbPrompt;
}

-(void) addConstaint
{
    //toolView的约束
    _toolView.translatesAutoresizingMaskIntoConstraints = NO;
    NSArray *toolViewContraintH = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_toolView]|" options:0 metrics:0 views:NSDictionaryOfVariableBindings(_toolView)];
    [self.view addConstraints:toolViewContraintH];

    NSArray * tooViewConstraintV;
    if (XIPHONE) {
        tooViewConstraintV = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[_toolView(49)]-35-|" options:0 metrics:0 views:NSDictionaryOfVariableBindings(_toolView)];
    } else {
        tooViewConstraintV = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[_toolView(49)]|" options:0 metrics:0 views:NSDictionaryOfVariableBindings(_toolView)];
    }
    [self.view addConstraints:tooViewConstraintV];
    self.tooViewConstraintHeight = tooViewConstraintV[0];
}

-(void)setToolViewBlock
{
    __weak __block TakePhotoViewController *copy_self = self;
    
    //回调输入框的contentSize,改变工具栏的高度
    [self.toolView setContentSizeBlock:^(CGSize contentSize) {
        [copy_self updateHeight:contentSize];
    }];

    //通过block回调接收到toolView中的text
    [self.toolView setMyTextBlock:^(NSString *myText) {
        WLog(@"%@",myText);
        [copy_self sendMessage:SendText Content:myText];
    }];

    //扩展功能回调
    [self.toolView setExtendFunctionBlock:^(int buttonTag) {
        switch (buttonTag) {
            case 1:
                //从相册获取
                [copy_self presentViewController:copy_self.imagePiceker animated:YES completion:^{

                }];
                break;
            case 2:
                //拍照
                #if TARGET_IPHONE_SIMULATOR

                    WLog(@"模拟器中无法打开照相机,请在真机中使用");
                    [WShareUtil showAlert:@"温馨提示" message:@"模拟器中无法打开照相机,请在真机中使用"];
                    return;
                #define SIMULATOR_TEST
                #else

                if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
                    
                    AVAuthorizationStatus authStatus =  [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
                    
                    if (authStatus == AVAuthorizationStatusDenied || authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusRestricted)
                    {
                        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
                        [alert show];
                        return;
                    }else {
                        copy_self.imagePiceker.delegate = copy_self;
                        copy_self.imagePiceker.allowsEditing = YES;//设置可编辑
                        copy_self.imagePiceker.sourceType = UIImagePickerControllerSourceTypeCamera;

                        [copy_self presentViewController:copy_self.imagePiceker animated:YES completion:^{
                        }];
                    }
                }

                #endif
                break;

            default:
                break;
        }
    }];

    //获取录音声量，用于声音音量的提示
    [self.toolView setAudioVolumeBlock:^(CGFloat volume) {

    }];

    //获取录音地址（用于录音播放方法）
    [self.toolView setAudioURLBlock:^(NSURL *audioURL) {

    }];

    //录音取消（录音取消后，把音量图片进行隐藏）
    [self.toolView setCancelRecordBlock:^(int flag) {

    }];

//    [self.messageLogMode setMyMessageBlock:^(HistoryMessageLog *myMessage) {
//        [copy_self.messageData addObject:myMessage];
//        [copy_self.timeArray addObject:myMessage.time];
//    }];
}

//更新toolView的高度约束
-(void)updateHeight:(CGSize)contentSize
{
    float height = contentSize.height;
    if (height <= 80) {
        [self.view removeConstraint:self.tooViewConstraintHeight];

        NSString *string = [NSString stringWithFormat:@"V:[_toolView(%f)]", height + 19];

        NSArray * tooViewConstraintV = [NSLayoutConstraint constraintsWithVisualFormat:string options:0 metrics:0 views:NSDictionaryOfVariableBindings(_toolView)];
        self.tooViewConstraintHeight = tooViewConstraintV[0];
        [self.view addConstraint:self.tooViewConstraintHeight];
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.messageData count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HistoryMessageLog *message = [self.messageData objectAtIndex:indexPath.row];
    NSDictionary *timeDict = [self timeOperate:(NSInteger)indexPath.row];
    NSString *bodyStr = message.body;
    NSData * bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:bodyData options:NSJSONReadingAllowFragments error:nil];
    MySendContentType contentType = [[dic objectForKey:@"type"] integerValue];

    if (self.isFirst) {    //一出来就能拉倒最后一行
        [self scrollBottom];
        self.isFirst = NO;
    }

    switch (contentType) {
        case SendText:
        {
            if ([message.tab boolValue]) {
                myTextCell *cell = [myTextCell cellWithTableView:tableView];
                NSMutableAttributedString *contentText = [self showFace:dic[@"content"]];
                [cell setCellValue:contentText andTimeDict:timeDict];
                return cell;
            }
            else
            {
                textCell *cell = [textCell cellWithTableView:tableView];
                NSMutableAttributedString *contentText = [self showFace:dic[@"content"]];
                [cell setCellValue:contentText andTimeDict:timeDict];
                return cell;
            }
        }
            break;
        case SendImage:
            if ([message.tab boolValue]) {
                myImageCell *cell = [myImageCell cellWithTableView:tableView];
                [cell setCellValue:dic[@"content"]];
                return cell;
            }
            else
            {
                imageCell *cell = [imageCell cellWithTableView:tableView];
                [cell setCellValue:dic[@"content"]];
                return cell;
            }
            break;
        case SendVoice:
            if ([message.tab boolValue]) {
                voiceCell *cell = [voiceCell cellWithTableView:tableView];
                NSURL *voiceURL = [NSURL URLWithString: dic[@"content"]];
                [cell setCellValue:voiceURL];
                return cell;
            }
            else
            {
                voiceCell *cell = [voiceCell cellWithTableView:tableView];
                NSURL *voiceURL = [NSURL URLWithString: dic[@"content"]];
                [cell setCellValue:voiceURL];
                return cell;
            }

            break;

        default:
            break;
    }
    UITableViewCell *cell = [[UITableViewCell alloc]init];
    return cell;
}

-(NSDictionary *)timeOperate:(NSInteger)row
{
    BOOL isShow = YES;
    NSString *showTime = [[NSString alloc]init];
    NSInteger count = [self.timeArray count];

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat : @"yyyy-M-d HH:mm"];

    WLog(@"%ld",(long)row);

    if (count == 1 || row == 0) {    //当只有一条的时候必须显示时间
        //WLog(@"%@",[formatter stringFromDate:[self.timeArray objectAtIndex:row]]);
        isShow = YES;
        showTime = [formatter stringFromDate:[self.timeArray objectAtIndex:row]];
    }
    else
    {
        //WLog(@"%@",[formatter stringFromDate:[self.timeArray objectAtIndex:row]]);
        //WLog(@"%@",[formatter stringFromDate:[self.timeArray objectAtIndex:row - 1]]);
        NSTimeInterval secondsInterval= [[self.timeArray objectAtIndex:(row)] timeIntervalSinceDate:[self.timeArray objectAtIndex:row - 1]];
        if (secondsInterval <= 60) {
            isShow = NO;
        }
        else
        {
            showTime = [formatter stringFromDate:[self.timeArray objectAtIndex:row]];
            isShow = YES;
        }
    }
//    WLog(@"%@",time);
//    WLog(@"%ld + %ld + %ld +%ld",(long)[components day],(long)[components hour],(long)[components minute],(long)[components second]);
    NSDictionary *timeDict = @{@"isShow":[NSNumber numberWithBool:isShow],@"showTime":showTime};
    return timeDict;
}

//发送消息
-(void)sendMessage:(MySendContentType) sendType Content:(id)content
{

    if ([WShareUtil strNilOrEmpty:content]) {
        return;
    }
    NSDictionary *bodyDic;

    if ([content isKindOfClass:[NSURL class]]) {

        bodyDic = @{@"type":@(sendType),
                    @"content":[NSString stringWithFormat:@"%@",content]};
    }
    else
    {
        bodyDic = @{@"type":@(sendType),
                    @"content":content};

    }

    //把bodyDic转换成data类型
    NSError *error = nil;
    NSData *bodyData = [NSJSONSerialization dataWithJSONObject:bodyDic options:NSJSONWritingPrettyPrinted error:&error];
    if (error)
    {
        WLog(@"解析错误%@", [error localizedDescription]);
    }

    //把data转成字符串进行发送
    NSString *bodyString = [[NSString alloc] initWithData:bodyData encoding:NSUTF8StringEncoding];

    HistoryMessageLog *message = [[HistoryMessageLog alloc]init];
     message.body = bodyString;
     message.from = @"test";
     message.to = @"test";
     message.tab = [NSNumber numberWithBool:1];
     message.time = [NSDate date];

    //发送数据给服务器
    switch (sendType) {
        case SendText:
        {
            [self submitContent:content];
            break;
        }
        case SendImage:
        {
            if ([content containsString:@"http://"]) {
                UIImageView *imgView = [[UIImageView alloc] init];
                [imgView sd_setImageWithURL:[NSURL URLWithString:content] placeholderImage:nil];
                [self uploadPhotoImage:imgView.image];
            } else {
                UIImageView *imgView = [[UIImageView alloc] init];
                imgView.image = [[UIImage alloc] initWithContentsOfFile:content];
                NSData *data = UIImageJPEGRepresentation(imgView.image, 0.1);
                UIImage *resultImage = [UIImage imageWithData:data];
                [self uploadPhotoImage:resultImage];
            }
            break;
        }
        default:
            break;
    }
    [self.messageData removeAllObjects];
//    //添加到数组里，刷新
//    [self.messageData addObject:message];
//    [self.timeArray addObject:message.time];
//
//    [self.messageData addObject:messageFrist];
//
//    [self.chatTableView reloadData];

}

//获取图片后要做的方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *pickerImage = info[UIImagePickerControllerEditedImage];

    //保存进沙盒，得到nsurl，保存
    NSString *strUrl = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *imageURL = [strUrl stringByAppendingPathComponent:[NSString stringWithFormat:@"%ld.png", (long)[[NSDate date] timeIntervalSince1970]]];

    [UIImagePNGRepresentation(pickerImage) writeToFile:imageURL atomically:YES];
    [self sendMessage:SendImage Content:imageURL];
    [self dismissViewControllerAnimated:YES completion:^{}];

}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    //在ImagePickerView中点击取消时回到原来的界面
    [self dismissViewControllerAnimated:YES completion:^{}];
    
}

//显示表情,用属性字符串显示表情
-(NSMutableAttributedString *)showFace:(NSString *)str
{
    if (str != nil) {
        //加载plist文件中的数据
        NSBundle *bundle = [NSBundle mainBundle];
        //寻找资源的路径
        NSString *path = [bundle pathForResource:@"emoticons" ofType:@"plist"];
        //获取plist中的数据
        NSArray *face = [[NSArray alloc] initWithContentsOfFile:path];

        //创建一个可变的属性字符串

        NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:str];

        UIFont *baseFont = [UIFont systemFontOfSize:17];
        [attributeString addAttribute:NSFontAttributeName value:baseFont
                                range:NSMakeRange(0, str.length)];

        //正则匹配要替换的文字的范围
        //正则表达式
        NSString * pattern = @"\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]";
        NSError *error = nil;
        NSRegularExpression * re = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];

        if (!re) {
            WLog(@"%@", [error localizedDescription]);
        }

        //通过正则表达式来匹配字符串
        NSArray *resultArray = [re matchesInString:str options:0 range:NSMakeRange(0, str.length)];


        //用来存放字典，字典中存储的是图片和图片对应的位置
        NSMutableArray *imageArray = [NSMutableArray arrayWithCapacity:resultArray.count];

        //根据匹配范围来用图片进行相应的替换
        for(NSTextCheckingResult *match in resultArray) {
            //获取数组元素中得到range
            NSRange range = [match range];

            //获取原字符串中对应的值
            NSString *subStr = [str substringWithRange:range];

            for (int i = 0; i < face.count; i ++)
            {
                if ([face[i][@"chs"] isEqualToString:subStr])
                {

                    //face[i][@"gif"]就是我们要加载的图片
                    //新建文字附件来存放我们的图片
                    NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];

                    //给附件添加图片
                    textAttachment.image = [UIImage imageNamed:face[i][@"png"]];

                    //把附件转换成可变字符串，用于替换掉源字符串中的表情文字
                    NSAttributedString *imageStr = [NSAttributedString attributedStringWithAttachment:textAttachment];

                    //把图片和图片对应的位置存入字典中
                    NSMutableDictionary *imageDic = [NSMutableDictionary dictionaryWithCapacity:2];
                    [imageDic setObject:imageStr forKey:@"image"];
                    [imageDic setObject:[NSValue valueWithRange:range] forKey:@"range"];

                    //把字典存入数组中
                    [imageArray addObject:imageDic];

                }
            }
        }
        //从后往前替换
        for (int i = (int)imageArray.count -1; i >= 0; i--)
        {
            NSRange range;
            [imageArray[i][@"range"] getValue:&range];
            //进行替换
            [attributeString replaceCharactersInRange:range withAttributedString:imageArray[i][@"image"]];
        }
        return  attributeString;
    }
    return nil;
}

-(void) scrollBottom
{
    if ([self.messageData count]) {
        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:self.messageData.count-1 inSection:0];
        [self.chatTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.y < 0  && _isRefresh==NO && _isFirst == NO)
    {
        NSString *num = [NSString stringWithFormat:@"%d",++j];
        [self requestListDataStrNum:num];
    }
}

-(UIActivityIndicatorView *)activity {
    if (_activity == nil) {
        UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 20)];
        self.activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        self.activity.frame = CGRectMake(headerView.frame.size.width/2, 0, 20, 20);
        [headerView addSubview:self.activity];
        self.chatTableView.tableHeaderView = headerView;
    }
    return _activity;
}

-(void)loadMoreHistoryData:(NSArray *)fetchArray
{
    [self.messageData removeObject:messageFrist];
    NSInteger fetchCount = [fetchArray count];
    if (fetchCount != 1) {  //数据加载完成
        [self activity];
        self.chatTableView.tableHeaderView.hidden = NO;
        [self.activity startAnimating];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            for (NSInteger i = 0; i < fetchCount; i ++) {
                [self.messageData insertObject:fetchArray[i] atIndex:i];
                [self.timeArray insertObject:((HistoryMessageLog *)fetchArray[i]).time atIndex:0];
            }
            WLog(@"%@",self.messageData);
            [self.messageData addObject:messageFrist];

            [self.chatTableView reloadData];

            [self.activity stopAnimating];
            self.chatTableView.tableHeaderView.hidden = YES;
            self.isRefresh = NO;
        });
    }
}

- (void)requestListDataStrNum:(NSString *)pageNum {

    _isRefresh = YES;
    NSString *userName;
    if ([WShareUtil sharedData].dicSession) {
        userName = [WShareUtil sharedData].dicSession[@"nsrsbh"];
    } else {
        return;
    }
    NSDictionary *parametersDict = @{@"mode":@"native",@"service":@"sjpai",@"content":@{@"revert":@"paginate",@"username":userName,@"pagesize":@"10",@"pagenumber":pageNum}};
    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];
    //    NSDictionary *paramsDic = @{@"params":[CommonFunc encryptWithText:secret]};
    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];
        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];
        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        NSMutableArray *fetchArray = [NSMutableArray array];
        for (NSDictionary *dic in returnDic[@"data"]) {
            HistoryMessageLog *messageLog = [[HistoryMessageLog alloc] init];

            NSNumber *numType;
            if ([dic[@"ispic"] isEqualToString:@"0"]) {
                numType = [NSNumber numberWithBool:0];
            } else {
                numType = [NSNumber numberWithBool:1];
            }
            //把bodyDic转换成data类型
            NSError *error = nil;
            NSData *bodyData = [NSJSONSerialization dataWithJSONObject:@{@"type":numType,@"content":dic[@"con"]} options:NSJSONWritingPrettyPrinted error:&error];
            if (error)
            {
                WLog(@"解析错误%@", [error localizedDescription]);
            }

            //把data转成字符串进行发送
            NSString *bodyString = [[NSString alloc] initWithData:bodyData encoding:NSUTF8StringEncoding];
            messageLog.body = bodyString;
            messageLog.from = @"test";
            messageLog.to = @"test";
            if ([dic[@"type"] isEqualToString:@"0"]) {
                messageLog.tab = [NSNumber numberWithBool:1];
            } else {
                messageLog.tab = [NSNumber numberWithBool:0];
            }
            messageLog.time = [NSDate date];
            [fetchArray addObject:messageLog];

        }
        [self loadMoreHistoryData:fetchArray];

    } failure:^(NSError *error) {
        WLog(@"失败");
    } showProgress:NO];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HistoryMessageLog *message = [self.messageData objectAtIndex:indexPath.row];

    NSString * bodyStr = message.body;
    NSData * bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:bodyData options:NSJSONReadingAllowFragments error:nil];

    //根据文字计算cell的高度
    if ([dic[@"type"] isEqualToNumber:@(SendText)]) {
        NSMutableAttributedString *contentText = [self showFace:dic[@"content"]];

        CGRect textBound = [contentText boundingRectWithSize:CGSizeMake(220, 1000) options:NSStringDrawingUsesLineFragmentOrigin context:nil];

        float height = textBound.size.height + 60;
        return height;
    }
    if ([dic[@"type"] isEqualToNumber:@(SendVoice)])
    {
        return 73;
    }

    if ([dic[@"type"] isEqualToNumber:@(SendImage)])
    {
        return 200;
    }

    return 100;

}

//键盘出来的时候调整tooView的位置
-(void) keyChange:(NSNotification *) notify
{
    NSDictionary *dic = notify.userInfo;

    CGRect endKey = [dic[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];
    //坐标系的转换
    CGRect endKeySwap = [self.view convertRect:endKey fromView:self.view.window];
    //运动时间
    [UIView animateWithDuration:[dic[UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{

        [UIView setAnimationCurve:[dic[UIKeyboardAnimationCurveUserInfoKey] doubleValue]];
        CGRect frame = self.view.frame;

        frame.size.height = endKeySwap.origin.y;

        self.view.frame = frame;
        [self.view layoutIfNeeded];
    }];
}

-(void)keyBoardDown:(id)sender
{
    [self.toolView keyboardDown];
}

- (void)dealloc {
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
}

// 发表文字上传
- (void)submitContent:(NSString *)strIssue {

    NSString *userName;
    if ([WShareUtil sharedData].dicSession) {
        userName = [WShareUtil sharedData].dicSession[@"nsrsbh"];
    } else {
        return;
    }
    NSDictionary *parametersDict = @{@"mode":@"native",@"service":@"sjpai",@"content":@{@"revert":@"submit",@"username":userName,@"con":strIssue,@"ispic":@"0"}};
    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];
    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];
        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];

        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        [self requestListDataStrNum:@"1"];
        j = 1;

        [SVProgressHUD showImage:nil status:returnDic[@"errorInfo"]];
        [SVProgressHUD setOffsetFromCenter:UIOffsetMake(0, WSCREENH_HEIGHT *0.5 - 70)];
        [SVProgressHUD dismissWithDelay:1.];
        [SVProgressHUD setBackgroundColor:[UIColor colorWithRed:0.9 green:0.91 blue:0.93 alpha:1]];

    } failure:^(NSError *error) {
        WLog(@"失败");
    } showProgress:NO];
}

// 发表图片上传
//上传图片(单张)
- (void)uploadPhotoImage:(UIImage*)image
{
    NSString *url;
    if (PCReleaseFlag) {
        url = @"http://www.sx95113.com/upload/upload_sjp";
    } else {
        url = @"http://www.icdes.cn/upload/upload_sjp";
    }

    NSString *fileName = [NSString stringWithFormat:@"%@.jpg",[WShareUtil timeString]];

    //3. 图片二进制文件
    NSData *imageData = UIImageJPEGRepresentation(image, 0.7f);
    WLog(@"upload image size: %ld k", (long)(imageData.length / 1024));

    //创建AFHTTPSessionManager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //设置响应文件类型为JSON类型
    manager.responseSerializer  = [AFJSONResponseSerializer serializer];
    //初始化requestSerializer
    manager.requestSerializer   = [AFHTTPRequestSerializer serializer];

    manager.responseSerializer.acceptableContentTypes = nil;
    //设置timeout
    [manager.requestSerializer setTimeoutInterval:50];
    //设置请求头类型
    [manager.requestSerializer setValue:@"form/data" forHTTPHeaderField:@"Content-Type"];
    [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>_Nonnull formData) {
        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpeg"];

    } progress:^(NSProgress * _Nonnull uploadProgress) {
        WLog(@"上传进度: %f", uploadProgress.fractionCompleted);
    } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
        //上传成功时的回调
        //        [hud hideAnimated:YES];
        NSString *messageStr = [responseObject objectForKey:@"message"];
        NSString *successStr = [responseObject objectForKey:@"success"];
        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];

        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        if ([successStr isEqualToString:@"true"]) {
            [self submitImageUrl:returnDic[@"link"]];
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //失败时的回调
        WLog(@"上传失败: %@", error);
    }];
}

- (void)submitImageUrl:(NSString *)imageUrl {

    NSString *userName;
    if ([WShareUtil sharedData].dicSession) {
        userName = [WShareUtil sharedData].dicSession[@"nsrsbh"];
    } else {
        return;
    }
    NSDictionary *parametersDict = @{@"mode":@"native",@"service":@"sjpai",@"content":@{@"revert":@"submit",@"username":userName,@"con":imageUrl,@"ispic":@"1"}};
    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];
    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];
        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];
       
        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        [self requestListDataStrNum:@"1"];
        j = 1;

    } failure:^(NSError *error) {
        WLog(@"失败");
    } showProgress:NO];
}


@end
